#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :List_Operator_28.py
# @Time      :2020/6/23 9:43
# @Author    :Administrator
import random

li = ["a", "b", "mplgrim", "z", "example"]
print(li[1])

# list 负数索引
print(li[-1])
print(li[-3])
print(li[1:3])
print(li[1:-1])
print(li[0:3])

# 增加元素
li.append("new")
print(li)
li.insert(2, "new")
print(li)
li.extend(["two", "elements"])
print(li)

# 搜索
print(li.index("example"))
print(li.index("new"))
# print(li.index("c"))  # 找不到报错

# 删除元素
li.remove("z")
print(li)
li.remove("new")
print(li)

# li.remove("c")    # list中没有找到值，会引发一个异常
ele = li.pop()
print(ele)
print(li)

# list 运算符
li = ['a', 'b', 'mpilgrim']
li = li + ['example', 'new']
print(li)
li += ["two"]
print(li)

li = [1, 2] * 3
print(li)

# 分割字符串
params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}
print(["%s=%s" % (k, v) for k, v in params.items()])
s = ";".join(["%s=%s" % (k, v) for k, v in params.items()])
print(s)
print(s.split(";"))
print(s.split(";", 1))  # split 接受一个可选的第二个参数，它是要分割的次数

# list的映射解析
li = [1, 9, 8, 4]
print([elem * 2 for elem in li])

# dictionary 中的解析
params = {"server": "mpilgrim", "database": "master", "uid": "sa", "pwd": "secret"}
print(params.keys())  # 注意，不是列表
print(params.values())  # 注意，不是列表
print(params.items())  # 注意，不是列表

print([k for k, v in params.items()])  # 获取字典key，转为列表
print([v for k, v in params.items()])  # 获取字典value，转为列表

# list过滤
li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
print(li)
print([ele for ele in li if len(ele) > 1])
print([ele for ele in li if ele != "b"])
print([ele for ele in li if li.count(ele) == 1])
